package com.app.newcsc.fragment.my.task;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.databinding.FragmentMyTaskTabBinding;
import com.app.newcsc.entity.Message;
import com.app.newcsc.view.InputPwdDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * @author: woking
 * @date: 2021/6/9
 * @description：
 */
public class TaskTabFragment extends BaseFragment<FragmentMyTaskTabBinding, TaskTabViewModel> {
    private int type = 0;
    public static TaskTabFragment newInstance(int invitationType) {
        TaskTabFragment fragment = new TaskTabFragment();
        Bundle args = new Bundle();
        args.putInt("Type", invitationType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initParam() {
        super.initParam();
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_my_task_tab;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public TaskTabViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(TaskTabViewModel.class);
    }

    @Override
    public void initData() {
        if (getArguments() != null) {
            type = getArguments().getInt("Type");
            viewModel.type.setValue(type);
        }
        initSubscription();
        binding.myrecyclerview.setEmptyView(binding.emptyView);
        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
        binding.setAdapter(new BindingRecyclerViewAdapter());
//        //请求网络数据
//        viewModel.requestNetWork(false);
//        showDialog("");

        initRefreshLayout();
    }


    public boolean isFirstLoad = true;
    @Override
    public void onResume() {
        super.onResume();
//        Log.e("TAG","============onResume======HTTP======");
        if (isFirstLoad)
        {
            // 将数据加载逻辑放到onResume()方法中
            showDialog("");
            //请求网络数据
//            viewModel.requestNetWork(false);
            binding.twinklingRefreshLayout.autoRefresh();
            isFirstLoad = false;
        }
    }

    private void initRefreshLayout()
    {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.onRefresh();
            }
        });
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.onLoadMore();
            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishRefresh();
                dismissDialog();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishLoadMore();
            }
        });
        //监听删除条目
//        viewModel.deleteItemLiveData.observe(this, new Observer<TaskTabItemViewModel>() {
//            @Override
//            public void onChanged(TaskTabItemViewModel netWorkItemViewModel) {
//                int index = viewModel.getItemPosition(netWorkItemViewModel);
//                //删除选择对话框
//                MaterialDialogUtils.showBasicDialog(getContext(), "提示", "是否删除【" + netWorkItemViewModel.entity.get().getName() + "】？ position：" + index)
//                        .onNegative(new MaterialDialog.SingleButtonCallback() {
//                            @Override
//                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                ToastUtils.showShort("取消");
//                            }
//                        }).onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        viewModel.deleteItem(netWorkItemViewModel);
//                    }
//                }).show();
//            }
//        });


        viewModel.duihuanItemLiveData.observe(this, new Observer<TaskTabItemViewModel>() {
            @Override
            public void onChanged(TaskTabItemViewModel taskTabItemViewModel) {
//                ToastUtils.showShort("点击兑换");
                getMemberBaseInfo(taskTabItemViewModel);
            }
        });
        viewModel.clickDuiHuan.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
//                Log.e("TAG",type+"====type=====HTTP====clickDuiHuan========s======"+s);
//                if(type == 1)
//                {
//                    //请求网络数据
//                    viewModel.requestNetWork(false);
//                }
            }
        });
    }
    private InputPwdDialog inputPasswordDialog;
    private void getMemberBaseInfo(TaskTabItemViewModel model) {
        inputPasswordDialog = new InputPwdDialog(getContext(), new InputPwdDialog.InputPasswordListener() {
            @Override
            public void callbackPassword(String password) {
//                Log.e("TAG","====states====callbackPassword=====password=="+password);
//                viewModel.createFinanceProductOrder(model.entity.get().id+"",model.entity.get().max_num+"",password);
                viewModel.createFinanceProductOrder(model.entity.get().id+"","1",password);
            }
        });
        inputPasswordDialog.setOnDismissListener(dialog -> {

        });
        inputPasswordDialog.show();
    }


    private Disposable mSubscription;
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
    }
    private void initSubscription()
    {
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG","===============message=============="+message.getName());
                        if(message.getName().equals("RefreshExchangeTask"))
                        {
                            //请求网络数据
//                            viewModel.requestNetWork(false);
                            binding.twinklingRefreshLayout.autoRefresh();
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }

}